// pages/shoppingVolume/privilege/privilege.js
import store from "../../../resource/lib/mystore";

let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    status: app.globalData.statusHeight, //头部占位高度
    navHeight: app.globalData.navHeight, //头部内容区
    ruleDescription: '', // 特权说明
    nodes: [
      {
        name: 'div',
        attrs: {
          class: 'div_class',
          style: 'line-height: 60px; color: red;',
        },
        // children: [{
        //   type: 'text',
        //   text: 'Hello&nbsp;World11111!'
        // }]
      },
    ],
    shareIt: 1,
    type: 2, //1是399  2是1999
    infoData:null, // 缓存的用户信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if (options) {
      // 卡片解析
      if (options.code) {
        app.store.setState({
          invite_code: options.code
            ? options.code
            : app.store.$state.invite_code,
        });
        that.setData({
          invite_code: options.code ? options.code : '',
          type: options.type ? options.type : '',
        });
      }
      if (options.type) {
        that.setData({
          type: options.type,
        });
      }
      // 二维码解析
      if (options.scene) {
        let scene = decodeURIComponent(options.scene);
        var arrPara = scene.split('&');
        var arr = [];
        for (var i in arrPara) {
          arr = arrPara[i].split('=');
          if (i == 0) {
            app.store.setState({
              invite_code: arr[1],
            });
            that.setData({
              invite_code: arr[1],
            });
          } else if (i == 1) {
            app.store.setState({
              uid: arr[1] ? arr[1] : '',
            });
            that.setData({
              uid: arr[1] ? arr[1] : '',
            });
          } else {
            that.setData({
              productId: arr[1] ? arr[1] : '',
            });
            app.store.setState({
              id: arr[1] ? arr[1] : '',
            });
          }
        }
      }
      if (that.data.invite_code) {
        that.setData({
          shareIt: 2,
        });
      }
    }
    //判断onLaunch是否执行完毕
    if (app.globalData.checkLogin) {
      that.reqIntfc();
    } else {
      app.checkLoginReadyCallback = (res) => {
        that.reqIntfc();
      };
    }
  },
  onShow(){
    console.log('onShow---');
    let infoData = wx.getStorageSync('infoData');
    if (infoData.level != 5){
      wx.hideShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })
    } else {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }
    this.setData({
      infoData: infoData,
    });
  },
  // 请求接口
  reqIntfc() {
    let that = this;
    that.index_getInfo();
    if (app.store.$state.invite_code) {
      that.bindInvitationCd();
      that.setData({
        shareIt: 2,
      });
    }
  },
  // 获取优惠卷详情
  index_getInfo() {
    let that = this;
    app.http({
      url: app.api.index_getInfo,
      data: {
        type: that.data.type,
      },
    })
      .then((res) => {
        that.setData({
          getVolume: res.data.data,
        });
      })
      .catch((err) => {});
  },
  // 购买按钮
  btn() {
    let that = this;
    app.http({
      url: app.api.post_my_rechargeVolume,
      data: {
        id: that.data.getVolume.id,
        code: that.data.invite_code,
      },
    })
      .then((res) => {
        wx.requestPayment({
          //调起支付
          //下边参数具体看微信小程序官方文档
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.package,
          signType: res.data.data.signType,
          paySign: res.data.data.paySign,
          success(res) {
            // wx.requestSubscribeMessage({
            // 	tmplIds: [
            // 		'FddT6-1bVu2lfiggUR7FVmS0mwrvTlGIgksy6xh94XE',
            // 	],
            // 	success(res) {},
            // });
            // 微信支付ok 直接跳转到我的订单列表
            if (res.errMsg == 'requestPayment:ok') {
              wx.navigateTo({
                url:
                  '/pages/shoppingVolume/recordsOfConsumption/recordsOfConsumption',
              });
            }
            that.get_my_getInfo();
          },
          fail(res) {},
        });
      })
      .catch((err) => {});
  },
  // 获取用户基本数据
  get_my_getInfo() {
    let that = this;
    // 登录
    wx.login({
      success(res) {
        let token = wx.getStorageSync('token');
        let header;
        if (token) {
          header = {
            Authorization: token,
          };
        } else {
          header = {};
        }
        if (res.code) {
          app.http({
            url: '/user/login/wxLogin',
            data: {
              code: res.code,
            },
            header: header,
          })
            .then((res) => {
              that.setData({
                infoData:res.data.data
              })
              console.log('res.data.data---',res.data.data);
              store.setState({
                infoData: res.data.data,
                token: res.data.data.token,
              });
              if (res.data.data.phone == '0') {
                store.setState({ loginType: 1 });
              } else {
                store.setState({ loginType: 0 });
              }
              wx.setStorageSync('infoData', res.data.data);
              wx.setStorageSync('token', res.data.data.token);
              that.globalData.checkLogin = true;
              //由于这里是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.checkLoginReadyCallback) {
                that.checkLoginReadyCallback(res);
              }
            })
            .catch((err) => {});
        }
      },
      fail: (err) => {},
    });
  },


  PhoneNumber(e) {
    let that = this;
    // 登录
    wx.login({
      success(res) {
        let header = {};
        if (res.code) {
          app.http({
            url: '/user/login/wxLogin',
            data: {
              code: res.code,
            },
            header: header,
          })
            .then((res) => {
              wx.setStorageSync('token', res.data.data.token);
              if (e.detail.iv) {
                app.http({
                  url: app.api.post_index_bindingPhone,
                  data: {
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                  },
                })
                  .then((res) => {
                    app.store.setState({
                      login: true,
                      getPhoneNumber: false,
                      loginType: 2,
                    });
                    that.btn();
                  })
                  .catch((err) => {});
              } else {
                wx.showToast({
                  title: '您取消了授权',
                  icon: 'none',
                  duration: 1500,
                });
              }
            })
            .catch((err) => {});
        }
      },
      fail: (err) => {},
    });
  },
  getPhone() {
    app.store.setState({
      getPhoneNumber: true,
    });
  },
  btn1() {
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */ onUnload: function () {
    app.store.setState({
      shareIt: 0,
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    let invite_code = app.store.getState().infoData.invite_code;
    let title = that.data.getVolume.title;
    let share = that.data.getVolume.share;
    if (res.from === 'menu') {
      return {
        title: title,
        path: `/pages/rights-and-interests/1999/index?code=${invite_code}&type=${that.data.type}`,
        imageUrl: share,
        success() {},
        fail() {},
        complete() {},
      };
    }
    return;
  },
});
